package com.wind.plugin.window;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.components.JBList;
import com.intellij.ui.components.JBScrollPane;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Map;

import static com.wind.plugin.window.Utils.findVirtualFile;
import static com.wind.plugin.window.Utils.openFile;
import static com.wind.plugin.window.Utils.showErrorDialog;


public class MissImCustNoPanel extends JPanel {
    private DefaultListModel<String> fileListModel;
    private JLabel missingTLabel;

    public MissImCustNoPanel(Project project) {
        setLayout(new BorderLayout());
        fileListModel = new DefaultListModel<>();
        JBList<String> fileList = new JBList<>(fileListModel);

        fileList.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    int index = fileList.locationToIndex(e.getPoint());
                    if (index >= 0) {
                        String selectedItem = fileListModel.getElementAt(index);
                        String selectedFilePath = selectedItem.split(": ", 2)[0].trim(); // 使用 ": " 分割，只分割第一次出现的 ": "
                        VirtualFile file = findVirtualFile(selectedFilePath);
                        if (file != null) {
                            openFile(project,file);
                        } else {
                            showErrorDialog(MissImCustNoPanel.this,"File not found: " + selectedFilePath);
                        }
                    }
                }
            }
        });

        add(new JBScrollPane(fileList), BorderLayout.CENTER);
        missingTLabel = new JLabel("Total Missing ImCustNo Fields Count: 0");
        add(missingTLabel, BorderLayout.NORTH);
    }

    public void update(Map<String, Integer> fileToMissingTCount) {
        SwingUtilities.invokeLater(() -> {
            fileListModel.clear();
            int totalMissingTCount = 0;
            for (Map.Entry<String, Integer> entry : fileToMissingTCount.entrySet()) {
                String fileName = entry.getKey();
                int count = entry.getValue();
                fileListModel.addElement(fileName + ": Missing ImCustNo Fields Count: " + count);
                totalMissingTCount += count;
            }
            missingTLabel.setText("Total Missing ImCustNo Fields Count: " + totalMissingTCount);
        });
    }
}
